package com.workingpub.commons.resource;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class ActivatorSupport implements BundleActivator {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private BundleContext bundleContext;

	@Override
	public void start(BundleContext context) throws Exception {
		this.bundleContext = context;
		try {
			doStartThings();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			throw e;
		}

	}

	@Override
	public void stop(BundleContext context) throws Exception {
		try {
			doStopThings();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			throw e;
		}
		this.bundleContext = null;
	}

	protected void doStartThings() throws Exception {
		logger.debug("Default implement, nothing to do. method : doStartThings");
	}

	protected void doStopThings() throws Exception {
		logger.debug("Default implement, nothing to do. method : doStopThings");
	}

	public BundleContext getBundleContext() {
		return bundleContext;
	}

	/**
	 * 在OSGi容器中查找相应服务实例
	 * 
	 * @param clazz
	 * @return 如果没有找到相应服务实例返回null，否则返回服务实例
	 */
	public <T extends Object> T getService(Class<T> clazz) {
		ServiceReference<T> serviceReference = bundleContext.getServiceReference(clazz);
		if (null == serviceReference) {
			logger.warn("The service reference cannot fount : {}", clazz);
			return null;
		}
		T instance = bundleContext.getService(serviceReference);
		if (null == instance) {
			logger.warn("The service instance cannot fount : {}", clazz);
			return null;
		}
		return instance;
	}
}
